package yl.hs.bmipfull.controllers.system;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yl.hs.bmipfull.controllers.ControllerBase;
import yl.hs.bmipfull.exception.UserAccountException;
import yl.hs.bmipfull.pojo.system.UserInfoEntity;
import yl.hs.bmipfull.service.system.ISearchViewService;
import yl.hs.bmipfull.service.system.IUserService;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.viewmodels.LoginUser;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.SubmitModel;
import yl.hs.bmipfull.viewmodels.WebResult;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 谢景广
 * @category 用户信息Web接口
 */
@Api(value = "用户信息Web接口", tags = "系统管理——用户管理")
@RequestMapping(path = "/api/system")
@RestController
public class UserController extends ControllerBase {

    @Autowired
    IUserService userSvc;
    @Autowired
    ISearchViewService svSVC;

    @RequestMapping(path = "/user/{rowNum}/{page}", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有用户", notes = "查询用户信息")
    @ResponseBody
    public WebResult queryAll(@RequestBody PageQuery query,
                              @PathVariable int page, @PathVariable int rowNum) {
        try {

            var result = userSvc.queryPage(query, rowNum, page);
            svSVC.updateUserMenuView(query);
            return success("ok", result);
        }
        catch (Exception ex){
            return error(ex);
        }
    }

    @ApiOperation(value = "查询所有用户", notes = "查询用户信息")
    @RequestMapping(path = "/selectUser", method = RequestMethod.GET)
    @ResponseBody
    public WebResult querySelectUsers() {
        var list = userSvc.queryAll().stream().filter(t->t.getAccount()!="admin").toList();
        var newList = list.stream().map(t -> {
            Map<String, Object> map = new HashMap<>();
            map.put("sn", t.getSn());
            map.put("userName", t.getRealname());
            map.put("mobile", t.getMobileNum());
            return map;
        }).collect(Collectors.toList());
        return success("ok", newList);
    }

    @ApiOperation(value = "查询所有用户", notes = "查询用户信息")
    @RequestMapping(path = "/selectUser/{organizationCode}", method = RequestMethod.GET)
    @ResponseBody
    public WebResult querySelectUsersByOrganizationCode(@ApiParam(value = "数据编号", required = true) @PathVariable("organizationCode") String organizationCode) {
        var list = userSvc.queryAlByOrganizationCode(organizationCode);
        var newList = list.stream().map(t -> {
            Map<String, Object> map = new HashMap<>();
            map.put("sn", t.getSn());
            map.put("userName", t.getRealname());
            map.put("mobile", t.getMobileNum());
            return map;
        }).collect(Collectors.toList());
        return success("ok", newList);
    }

    @ApiOperation(value = "保存用户信息", notes = "保存编辑或者新建的用户信息")
    @RequestMapping(path = "/updatePersonalInfo", method = RequestMethod.POST)
    @ResponseBody
    public WebResult updatePersonalInfo(@RequestBody SubmitModel model) {
        try {
            Integer result = userSvc.updatePersonalInfo(model);
            if (result > 0) {
                return success("数据保存成功");
            }
            return fail("保存失败");
        } catch (Exception ee) {
            return error(ee);
        }
    }
    @ApiOperation(value = "保存用户信息", notes = "保存编辑或者新建的用户信息")
    @RequestMapping(path = "/user", method = RequestMethod.POST)
    @ResponseBody
    public WebResult save(@RequestBody SubmitModel model) {
        try {
            Integer result = userSvc.save(model);
            if (result > 0) {
                return success("数据保存成功");
            }
            return fail("保存失败");
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "查询用户信息", notes = "查询根据用户编号获取用户信息")
    @RequestMapping(path = "/user/{sn}", method = RequestMethod.GET)
    @ResponseBody
    public WebResult find(@ApiParam(value = "数据编号", required = true) @PathVariable("sn") String sn) {
        try {
            var user = userSvc.findUserBySN(sn);
            if (user != null) {
                return success("ok", user);
            } else {
                return fail(String.format("没有找到编号为%s的用户信息", sn));
            }
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "删除用户信息", notes = "根据用户编号删除用户信息")
    @RequestMapping(path = "/user/{sn}", method = RequestMethod.DELETE)
    @ResponseBody
    public WebResult delete(@ApiParam(value = "数据编号", name = "sn", allowMultiple = true, required = true) @PathVariable("sn") String sn) {
        try {
            var result = userSvc.deleteUser(sn.split(","));
            if (result > 0) {
                return success("ok");
            }
            return fail("没有删除任何信息");
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @RequestMapping(path = "/user/current", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getUser() {
        LoginUser current = HsApp.getCurrent();
        if (current != null) {
            UserInfoEntity userInfo = userSvc.findUserBySN(current.getUserSN());
            Map<String, Object> map = new HashMap<>();

            map.put("userLogin", current);
            map.put("userInfo", userInfo);

            return success("查询成功", map);
        } else {
            return fail("查询失败");
        }

    }

    @ApiOperation(value = "修改密码", notes = "根据用户编号删除用户信息")
    @RequestMapping(path = "/user/changePassword", method = RequestMethod.PUT)
    public WebResult changePassword(@RequestBody SubmitModel model) {
        try {
            var result = userSvc.changePassword(model.getSn(), model.getData().get("oldPwd").toString(), model.getData().get("newPwd").toString());
            if (result > 0) {
                return success("修改成功");
            } else {
                return fail("修改失败");
            }
        } catch (UserAccountException ee) {
            return fail(ee.getMessage());
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "重置密码", notes = "根据用户编号重置密码")
    @RequestMapping(path = "/user/reset/{sn}", method = RequestMethod.GET)
    public WebResult RestPassword(@ApiParam(value = "用户sn") @PathVariable String sn) {
        if (userSvc.RestPassword(sn) > 0) {
            return success("重置成功");
        } else {
            return fail("重置失败");
        }
    }
}
